#!/usr/bin/env python3
import sys
import uvicorn
from database import init_db
from config import app_config, print_config

def setup_and_start():
    print("商品数据分析系统 - 启动脚本")
    print("=" * 50)
    print_config()
    
    print("\n正在初始化数据库...")
    try:
        init_db()
        print("✓ 数据库初始化完成")
    except Exception as e:
        print(f"✗ 数据库初始化失败: {e}")
        sys.exit(1)
    
    print(f"\n正在启动应用...")
    print(f"服务器地址: http://{app_config.HOST}:{app_config.PORT}")
    print(f"API文档: http://{app_config.HOST}:{app_config.PORT}/docs")
    print("按 Ctrl+C 停止服务")
    print("=" * 50)
    
    try:
        uvicorn.run(
            "main:app", 
            host=app_config.HOST, 
            port=app_config.PORT, 
            reload=app_config.DEBUG,
            log_level="info" if not app_config.DEBUG else "debug"
        )
    except KeyboardInterrupt:
        print("\n正在停止服务...")
    except Exception as e:
        print(f"启动失败: {e}")
        sys.exit(1)

if __name__ == "__main__":
    setup_and_start()
    print("启动成功")